package com.design.classroommanagement.api.dao

import com.design.classroommanagement.api.Bookmark
import com.design.classroommanagement.api.toMap
import com.design.classroommanagement.manager.UserAccountManager
import java.sql.ResultSet

object BookmarkDao : BaseDao<Bookmark> {
    override fun getData(rs: ResultSet): Bookmark {
        val user = Bookmark()
        user.id = rs.getDecodeObject("id")?.toString()
        user.tid = rs.getDecodeObject("tid")?.toString()
        user.name = rs.getDecodeObject("name")?.toString()
        user.classname = rs.getDecodeObject("classname")?.toString()
        user.date = rs.getDecodeObject("date")?.toString()
        user.progress = rs.getDecodeObject("progress")?.toString()?.toIntOrNull() ?: 0
        return user
    }

    override fun getTableName(): String {
        return "bookmark"
    }

    override fun getDbMap(t: Bookmark): HashMap<String, Any> {
        return t.toMap().apply {
            remove("id")
        }
    }

    suspend fun search(key: String): List<Bookmark> {
        var result = BookmarkDao.query {
            put("id", key)
            put("tid", UserAccountManager.uid)
        }
        if (result.isEmpty()) {
            result = BookmarkDao.query {
                put("name", key)
                put("tid", UserAccountManager.uid)
            }
        }
        return result
    }
}